package com.evry.spring3sandbox.web;

import java.math.BigDecimal;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;

import com.evry.spring3sandbox.service.PriceIncrease;

@Component("priceIncreaseValidation")
public class PriceIncreaseValidation {
	private static final BigDecimal DEFAULT_MIN_PERCENTAGE = BigDecimal
			.valueOf(0);
	private static final BigDecimal DEFAULT_MAX_PERCENTAGE = BigDecimal
			.valueOf(50);

	public boolean supports(Class<?> klass) {
		return PriceIncrease.class.isAssignableFrom(klass);
	}

	public void validate(Object target, Errors errors) {
		PriceIncrease priceIncrease = (PriceIncrease) target;
		if (priceIncrease.getPercentage() != null) {
			if (BigDecimal.valueOf(0.0).compareTo(priceIncrease.getPercentage()) == 0) {
				errors.rejectValue("percentage", "error.zero_percentage",
						"percentage cannot be 0!");
			}

			if (DEFAULT_MIN_PERCENTAGE.compareTo(priceIncrease.getPercentage()) > 0) {
				errors.rejectValue("percentage", "error.too-low",
						new Object[] { DEFAULT_MIN_PERCENTAGE },
						"percentage has to be more than 0");
			}
			if (DEFAULT_MAX_PERCENTAGE.compareTo(priceIncrease.getPercentage()) < 0) {
				errors.rejectValue("percentage", "error.too-high",
						new Object[] { DEFAULT_MAX_PERCENTAGE },
						"percentage no more than 50");
			}
		}
	}
}
